package com.smr.springboot.resttest.exception;

import com.smr.springboot.resttest.pojo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@Slf4j
//该注解用于处理异常
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 系统异常处理，比如：404,500
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseResult defaultErrorHandler(HttpServletRequest request, Exception e) throws Exception {
        log.error(e.getMessage(), e);
        ResponseResult<Object> result = new ResponseResult<>();
        result.setMessage(e.getMessage());
        if (e instanceof org.springframework.web.servlet.NoHandlerFoundException) {
            result.setErrorcode("404");
        } else {
            result.setErrorcode("500");
        }
        result.setData(null);
        result.setSuccess(false);
        return result;
    }
}
